package com.wdz.controller;


import com.jcraft.jsch.SftpException;
import com.wdz.http.Response;
//import com.wdz.tenxunyuncos.COSService;
import com.wdz.utils.FileUtil;
import com.wdz.utils.MultipartFileToFile;
import com.wdz.utils.tenxunyuncos.COSService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class UploadController {

    @Value("${app_file.basePath}")
    private String basePath;
    @Value("${app_file.host}")
    private String host;
    @Value("${cos.domain}")
    private String ym;
    @Value("${cos.bucketName}")
    private String bucketName;
    @Value("${cos.regionName}")
    private String regionName;

    /**
     * 普通上传文件接口
     * @param file
     * @param directory
     * @return
     * @throws IOException
     * @throws SftpException
     */
    @PostMapping("/upload")
    public Response upload(MultipartFile file, String directory,String fileName) throws Exception {
        if(fileName == null) {
            //根据uuid生成文件名
            fileName = FileUtil.makeFileName(file);
        }
        StringBuilder str = new StringBuilder();
        if (directory != null) {
            str.append("/");
            str.append(directory);
            str.append("/");
        }
        str.append(fileName);
        COSService.upload(regionName, MultipartFileToFile.multipartFileToFile(file), bucketName, str.toString());
        StringBuilder url = new StringBuilder(ym);
        url.append(str);
        return Response.success(url);
    }

    @PostMapping("/makeHtml")
    public Response makeHtml(@RequestParam String htmlValue,String directory,String qfileName){
        StringBuffer filePath = new StringBuffer(basePath);
        if(directory != null){
            filePath.append(directory);
            filePath.append("/");
        }
        //根据uuid生成文件名
        String fileName;
        if(StringUtils.isEmpty(qfileName)) {
            fileName = FileUtil.makeFileName();
        }else{
            fileName = qfileName;
        }
        if(FileUtil.strToMakeHtml(filePath.toString(),htmlValue,fileName)){
            StringBuffer url = new StringBuffer(host);
            if(directory != null){
                url.append(directory);
                url.append("/");
            }
            url.append(fileName);
            url.append(".html");
            return Response.success(url);
        }
        return Response.error();
    }

}
